package com.urbanski.clipboard.server.util;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import org.apache.log4j.Logger;
import com.urbanski.clipboard.common.util.CommonConstants;
import com.urbanski.clipboard.server.action.command.ServerActionHandler;
import com.urbanski.clipboard.server.util.ServerConstants.ServerCommand;
import com.urbanski.util.io.FileUtils;
import com.urbanski.util.logging.LoggingUtil;

public class ServerUtils
{
	private static final Logger LOGGER = Logger.getLogger(ServerUtils.class);
	
	private ServerUtils()
	{
	}
	
	public static void printHelp(ServerCommand command)
	{
		try
		{
			FileUtils.printFileByLine(new File(CommonConstants.COMMAND_HELP_FILE_TEMPLATE.replace("$keyword", command.getKeyword())));
		}
		catch (IOException e)
		{
			LoggingUtil.logAndPrintError(LOGGER, "Error displaying help file (" + CommonConstants.HELP_FILE + ")", e);
		}
	}

	public static void processCommand(ServerCommand command, String line, String[] tokens)
	{
		try
		{
			ServerActionHandler actionHandler = ServerActionHandler.getActionHandler(command, tokens);

			if (!actionHandler.processHelpCommand(tokens))
			{
				actionHandler.execute();
			}
		}
		catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e)
		{
			LOGGER.error("Could not get action handler for command " + command, e);
		}
		catch (IOException e)
		{
			LoggingUtil.logAndPrintError(LOGGER, "Error sending command to server", e);
		}
	}
}
